package com.nl.controller.common.interceptor;

import com.nl.controller.web.bean.SmsUsers;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserSecurityInterceptor implements HandlerInterceptor {

    private static Logger log = Logger.getLogger(UserSecurityInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        if (obj instanceof HandlerMethod) {
            HttpSession session = request.getSession();
            SmsUsers user = (SmsUsers) session.getAttribute("user");
            String url = request.getRequestURL().toString();
            log.error("url:"+url+request.getQueryString());
            //允许未登录访问的请求
            String[] allowUrls = new String[]{"/login", "/test", "/druid","/reset","resetPassword"};
            for (String strUrl : allowUrls) {
                if (url.contains(strUrl)
                        || user != null) {
                    SysContext.setRequest(request);
                    SysContext.setResponse(response);
                    return true;
                }
            }
            log.error("未登录或者登录过期...");
            response.sendRedirect(request.getContextPath() + "/login.html");
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
